<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once "src/apiClient.php";
require_once "src/contrib/apiCalendarService.php";
session_start();
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Gclient extends CI_Controller {
function __construct()
    {
        parent::__construct();
    	$this->load->library('session');
		$this->load->helper('url');
    	$this->load->database();
    	$this->load->model("centermod");
    	
	}
	
/******************* google api *******************************/

	function apigooglecalarapi()
	{
			$client = new apiClient();
			$client->setApplicationName("Google Calendar PHP Starter Application");

// Visit https://code.google.com/apis/console?api=calendar to generate your
// client id, client secret, and to register your redirect uri.
 $client->setClientId('770938131025-l8cip9cgo7gfgfqjfphhr7k8m2d608l2.apps.googleusercontent.com');
$client->setClientSecret('o6wpNT8E5ugqg1SfP6XWhTwu');
 $client->setRedirectUri('http://onclickconcept.ca/calendar/reponse.php');

$client->setDeveloperKey('AI39si6a39ey9Zl_elSjD3eTiJV7Aiav2FK3luNQweZGdvLckqPGINxRF349spYyrzESSINdA3kOQgQknnROREMKhzOtNg0Zvw');
$client->setUseObjects(true);
$cal = new apiCalendarService($client);
if (isset($_GET['logout'])) {
  unset($_SESSION['token']);
}

if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['token'] = $client->getAccessToken();
	 header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}

if (isset($_SESSION['token'])) {
  $client->setAccessToken($_SESSION['token']);
}
		
	return $client;
	}
	
	
/***##########################################################*/
/*******************  Page   *********************************/
function clientform()
	{
		if($this->session->userdata("user")==false)
			{
					header('Location:index.php?pages/loginadmin');
						
			}else 
			{
				$data=array("type"=>"add");
				$this->load->view("client_form",$data);
				
			}	
	}

	
	
// get edit form 
	function Editclientform($idclient)
	{
		if($this->session->userdata("user")==false)
			{
					header('Location:index.php?pages/loginadmin');
						
			}else 
			{
		
				$infoclient=$this->centermod->getclientinfobyid($idclient);
				$data=array("infoclient"=>$infoclient,"type"=>"edit");
				$this->load->view("client_form",$data);
	
			}	
		}	
/*#############################  end pages   ##############################*/

	

	
	
/*******************       add    *********************************/

function addclientinfo()
	{
			
			if($this->session->userdata("user")==false && $this->session->userdata("id")<=0)
			{
					header('Location:index.php?pages/loginadmin');
						
			}else 
			{
		
			$companyname=$this->input->get_post("companyname");
			$address=$this->input->get_post("address");
			$tele=$this->input->get_post("tele");
			$city=$this->input->get_post("city");
			$fax=$this->input->get_post("fax");
			$contactperson=$this->input->get_post("contactperson");
			$contactpersonemail=$this->input->get_post("contactpersonemail");
			  
      		$data=array(    "companyname"=>$companyname,
      						"address"=>$address,
      						"tele"=>$tele,
							"city"=>$city,
      						"fax"=>$fax,
      						"contactperson"=>$contactperson,
      						"contactpersonemail"=>$contactpersonemail
      					);
			if($companyname !="" && $address!="" && $tele!="")
				{
					$idinsert=$this->centermod-> insertetemplate("clients",$data);
					if($idinsert >0)
						{
								$iduser=$this->session->userdata("id");
								$idclient=$idinsert;
								$statusid=1;
								$data_fllowups=array(
														 "User_idUser"=>$iduser,
														 "clients_idclients"=>$idclient,
														 "status_idstatus"=>$statusid
													);
								$idinsert_follow=$this->centermod-> insertetemplate("casefollowups",$data_fllowups);
								$data_stores=array("clients_idclients"=>$idclient,"name"=>"base");
								$idinsert2=$this->centermod-> insertetemplate("stores",$data_stores);					
								//$this->load->view("listclient");
								//$this->listclient();
								 redirect('index.php?gclient/listclient', 'refresh');
						}else 
						{
							echo "system ne peut pas ajoute l'information de cleint";
						}
					
					
				}else
				{
					echo "name , email, adresse ne peux pas null"; 
				}
				
			
		}
	}	
	
	
	
/*#############################  end  add  #############################*/	
	
	

	
	
/**************************** list **************************************/
	function listclient()
	{
		if($this->session->userdata("user")==false && $this->session->userdata("id")<=0)
			{
					header('Location:index.php?pages/loginadmin');
						
			}else 
			{
				$listallclient=$this->centermod->listallclientbyiduser($this->session->userdata("id"));
				$data=array("listclient"=>$listallclient,"role"=>$this->session->userdata("role"));
				$this->load->view("listclient",$data);
				
				
			}
	}
	
	
function bookinglistuser()
{
	if($this->session->userdata("user")==false && $this->session->userdata("id")<=0)
			{
					header('Location:index.php?pages/loginadmin');
						
			}else 
			{
				$listbooking=$this->centermod->getuserappointbyuser($this->session->userdata("id"));
				$data=array("listbooking"=>$listbooking,"role"=>$this->session->userdata("role"));
				$this->load->view("listbookingbyuser",$data);	
						
			}
}	
/*############################end List #################################*/		
	
	
	
	
	
	
/*******************      Edit    *********************************/	
 function  editclient()
 {
 			
 	if($this->session->userdata("user")==false && $this->session->userdata("id")<=0)
			{
					header('Location:index.php?pages/loginadmin');
						
			}else {
					 	$idclient=$this->input->get_post("idclients");
						if($idclient>0)
					 	{
					 		$listallclient=$this->centermod->getclientinfobyid($idclient);
					 			$data=array("type"=>"edit","infoclient"=>$listallclient);
									$this->load->view("client_form",$data);
					 	} 
					 	else
					 	{
					 		echo"note good idclient";
					 	}
					 	
			} 	
  }

function submiteditclient()
{
	if($this->session->userdata("user")==false && $this->session->userdata("id")<=0)
			{
					header('Location:index.php?pages/loginadmin');
						
			}else
			{
			$companyname=$this->input->get_post("companyname");
			$address=$this->input->get_post("address");
			$tele=$this->input->get_post("tele");
			$city=$this->input->get_post("city");
			$fax=$this->input->get_post("fax");
			$contactperson=$this->input->get_post("contactperson");
			$contactpersonemail=$this->input->get_post("contactpersonemail");
			$idclients=$this->input->get_post("idclients");
			$data=array("companyname"=>$companyname,"address"=>$address,"tele"=>$tele,"city"=>$city,"contactperson"=>$contactperson,"contactpersonemail"=>$contactpersonemail);
			if ($idclients!="")
				{
					$this->centermod-> updatetemplate("clients",$data,"idclients =$idclients");
					
		//check if no stores exit , create un store base pour chaque  clients			
					$ckeresult=$this->centermod->ckebasestore($idclients);
					if($ckeresult==0)
					{
						$data_stores=array("clients_idclients"=>$idclients,"name"=>"base");
						$idinsert2=$this->centermod-> insertetemplate("stores",$data_stores);	
					}
					redirect("index.php?gclient/listclient",'refresh');
				
				}
			}
}	


function editclientstatus()
	{
			if($this->session->userdata("user")==false && $this->session->userdata("id")<=0)
			{
					header('Location:index.php?pages/loginadmin');
						
			}else
			{
				$idcase=$this->input->get_post("idcase");
				$statuslist=$this->centermod->statuslist();
				$statusinfo=$this->centermod->listestatusclientbyidcase($idcase);
				$data=array("statusinfo"=>$statusinfo,"statuslist"=>$statuslist);
				$this->load->view("client_status",$data);
	
			}
	}
	
//	action edit status
function actionstatus()
{
				if($this->session->userdata("user")==false && $this->session->userdata("id")<=0)
			{
					header('Location:index.php?pages/loginadmin');
						
			}else
			{
	
	$idcase=$this->input->get_post("idcase");
	$idstatus=$this->input->get_post("idstatus");
	$reminder=$this->input->get_post("reminder");
	$longtimefollowups=$this->input->get_post("longtimefollowups");
	$data=array("reminder"=>$reminder,"longtimefollowups"=>$longtimefollowups,"status_idstatus"=>$idstatus);
	if($idcase>0){
	$this->centermod-> updatetemplate("casefollowups",$data,"idcase=$idcase");
	redirect("index.php?gclient/listclient",'refresh');
	}else 
		{
			echo "no case selected";
		}
	}
}


//edit sales  booking 
function editbookinguser()
{
			if($this->session->userdata("user")==false && $this->session->userdata("id")<=0)
			{
					header('Location:index.php?pages/loginadmin');
						
			}else
			{
				$idappointments=$this->input->get_post("idappointments");
				$idgooglecalendor=$this->input->get_post("idgooglecalendor");
				$role=$this->input->get_post("role");
				$infoappointment=$this->centermod->getuserappointbyidpointement($idappointments);
				$forfaitlist=$this->centermod->forfaitlist();
				$data=array("infoappointment"=>$infoappointment,"forfaitlist"=>$forfaitlist,"role"=>$role);
				
				$this->load->view("editbookingform",$data);
			
			}
}


	
/*#############################  end  edit  #############################*/	




/*******************     booking photo show    *********************************/	

function bookingshowform()
{
			if($this->session->userdata("user")==false && $this->session->userdata("id")<=0)
			{
					header('Location:index.php?pages/loginadmin');
						
			}else
			{
				$idcase=$this->input->get_post("idcase");	
				if($idcase>0)
				{
					$clientinfo=$this->centermod->listestatusclientbyidcase($idcase);
					$forfaitlist=$this->centermod->forfaitlist();
					$username=$this->centermod->getnameuser($this->session->userdata("id"));
					$data=array("clientinfo"=>$clientinfo,"forfaitlist"=>$forfaitlist,"username"=>$username);
					$this->load->view("bookingform",$data);
				
				}else 
				{
						echo "no case selected error 259 gc";
				}
				
			}
}


function addappoitment()
{
			
	if($this->session->userdata("user")==false && $this->session->userdata("id")<=0)
			{
					header('Location:index.php?pages/loginadmin');
						
			}else
			{
			date_default_timezone_set('America/Montreal');
	 		$calendarid=$this->centermod->getoption("calendarid");
			$address=$this->input->get_post("address");
			$tele=$this->input->get_post("tele");
			$city=$this->input->get_post("city");
			$companyname=$this->input->get_post("companyname");
			//$linkgooglep=$this->input->get_post("linkgooglep");
			$Date=$this->input->get_post("Date");
			$strattime=$this->input->get_post("strattime");
			$endtime=$this->input->get_post("endtime");
			$forfait=$this->input->get_post("forfait");
			$Description=$this->input->get_post("Description");
			$decider=$this->input->get_post("decider");
			$d_tele=$this->input->get_post("d_tele");
			$d_email=$this->input->get_post("d_email");
			$sales=$this->input->get_post("sales");
			$idcase=$this->input->get_post("idcase");
			$idclients=$this->input->get_post("idclients");

	//create date start and date end
		$date1 = new DateTime($Date);
		$date1->setTimezone(new DateTimeZone('America/Montreal'));
		$date1->setTime($strattime, 00);
		$astart= date_format($date1, 'Y-m-d\TH:i:sP');

		//end
		$date2 = new DateTime($Date);
		$date2->setTimezone(new DateTimeZone('America/Montreal'));
		$date2->setTime($endtime, 00);
		$aend= date_format($date2, 'Y-m-d\TH:i:sP');	
	//----------------------	

	//get information forfait
	$infoforfait=$this->centermod->getforfaitnamebyid($forfait);
		
		
	$str_summary=$companyname." ".$address." ".$infoforfait[0]["name"]."-- $".$infoforfait[0]["prix"];

		$client=$this->apigooglecalarapi();
		$cal = new apiCalendarService($client);
		if ($client->getAccessToken()) {
			
		//-------insert event--------	
		$event = new Event();
		$event->setSummary($str_summary);
		$event->setDescription($Description	);	
		
		$event->setLocation($address);
		$start = new EventDateTime();
		$start->setDateTime($astart);
		$event->setStart($start);
		$end = new EventDateTime();
		$end->setDateTime($aend);
		$event->setEnd($end);
		$attendee1 = new EventAttendee();
		$attendee1->setEmail($d_email);
		$attendees = array($attendee1 );
		$event->attendees = $attendees;
		$createdEvent = $cal->events->insert($calendarid, $event);
		//echo $createdEvent->getId()."you booking addappoitment";
			
		//------------- add appointement a BASEDONNE--------------------
		$idstore=$this->centermod->getidstorebyidclient($idclients)	;
		if($idstore==0)
		{
			$data_stores=array("clients_idclients"=>$idclients,"name"=>"base");
			$idinsert2=$this->centermod-> insertetemplate("stores",$data_stores);
		}
		$data_appoint=array("idgooglecalendor"=>$createdEvent->getId(),"casefollowups_idcase"=>$idcase,
							"stores_idstores"=>$idstore,"forfait_idforfait"=>$forfait,"coments"=>$Description
							,"starttime"=>$astart,"endtime"=>$aend);
		$idinsert_appoint=$this->centermod-> insertetemplate("appointments",$data_appoint);
		
		
		redirect("index.php?gclient/bookinglistuser",'refresh');

	
// update event
	
	
	
	$_SESSION['token'] = $client->getAccessToken();
	
  
  



} else {
  $authUrl = $client->createAuthUrl();
  print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
}

}//addappoitment




//action edit booking 
function actioneditbookingsuer()
{
			
	if($this->session->userdata("user")==false && $this->session->userdata("id")<=0)
			{
					header('Location:index.php?pages/loginadmin');
						
			}else
			{
			date_default_timezone_set('America/Montreal');
	 		$idappointments=$this->input->get_post("idappointments");
	 		$idgooglecalendor=$this->input->get_post("idgooglecalendor");
			$calendarid=$this->centermod->getoption("calendarid");
			$Date=$this->input->get_post("Date");
			$strattime=$this->input->get_post("strattime");
			$endtime=$this->input->get_post("endtime");
			$forfait=$this->input->get_post("forfait");
			$Description=$this->input->get_post("Description");
			$titre=$this->input->get_post("titre");
			$role=$this->input->get_post("role");
			$infoforfait=$this->centermod->getforfaitnamebyid($forfait);
			$str_summary=$titre."-- $".$infoforfait[0]["prix"];
				
			$date1 = new DateTime($Date);
			$date1->setTimezone(new DateTimeZone('America/Montreal'));
			$date1->setTime($strattime, 00);
			$astart= date_format($date1, 'Y-m-d\TH:i:sP');
	
			//end
			$date2 = new DateTime($Date);
			$date2->setTimezone(new DateTimeZone('America/Montreal'));
			$date2->setTime($endtime, 00);
			$aend= date_format($date2, 'Y-m-d\TH:i:sP');	
			
			$infoforfait=$this->centermod->getforfaitnamebyid($forfait);
			
			$client=$this->apigooglecalarapi();
			$cal = new apiCalendarService($client);
			if ($client->getAccessToken()) {
 			


			//-------update event--------

			$calendarid=$this->centermod->getoption("calendarid");
			$event = $cal->events->get($calendarid, $idgooglecalendor);
			$event->setSummary($str_summary);
			$event->setDescription($Description	);	
			//$event->setLocation($address);
			$start = new EventDateTime();
			$start->setDateTime($astart);
			$event->setStart($start);
			$end = new EventDateTime();
			$end->setDateTime($aend);
			$event->setEnd($end);
			$cal->events->update($calendarid, $event->getId(), $event);
			//echo $createdEvent->getId()."you booking addappoitment";
	
//------------- add appointement a BASEDONNE--------------------
$data_appoint=array("forfait_idforfait"=>$forfait,"coments"=>$Description
					,"starttime"=>$astart,"endtime"=>$aend);
$where="idappointments=$idappointments";
$this->centermod->  updatetemplate("appointments",$data_appoint,$where);
if ($role=="user"){
redirect("index.php?gclient/bookinglistuser",'refresh');
}elseif ($role=="admin")
{
	redirect("index.php?gadmin/bookinglistadmin",'refresh');
}
	$_SESSION['token'] = $client->getAccessToken();
	
  
  



} else {
  $authUrl = $client->createAuthUrl();
  print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
			
			}
	
}



/*#############################  end  photo show  #############################*/	

}